package ddd.ajava.chapter7.question8;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

import net.sf.json.JSONObject;

public class Server {
	public static void main(String[] args) throws Exception{
		ServerSocket server = new ServerSocket(8010);
		
		while(true){
			Socket socket = server.accept();
			System.out.println("请求已接受");
			InputStream in = socket.getInputStream();
			BufferedReader br=new BufferedReader(new InputStreamReader(in));
			String requestStr=br.readLine();
			System.out.println("收到请求:"+requestStr);
			br.close();
			in.close();
			Object re=handleRequest(requestStr);
			
			OutputStream out=socket.getOutputStream();
			if(re.toString().equals("true")){
				out.write("执行成功！".toString().getBytes());
			}else{
				out.write("执行失败！".toString().getBytes());
			}
//			out.close();
//			socket.close();
//			server.close();
		}
	}
	
	public static Object handleRequest(String requestStr){
		String[] str=requestStr.split("\\(");
		for(String s:str){
			System.out.print("split json:"+s+"  ");
		}
		System.out.println("str[0]:"+str[0]);
		String[] canimalMethodName=str[0].split("\\.");
//		for(String s:canimalMethodName){
//			System.out.println("canonimal:"+s+"  ");
//		}
		int count=canimalMethodName.length;
		System.out.println("count:"+count);
		String methodName=canimalMethodName[count-1];
		String className=null;
		StringBuilder sb=new StringBuilder();
		for(int i=0;i<count-1;i++){
			sb.append(canimalMethodName[i].trim()+".");
		}
		className=sb.substring(0, sb.length()-1);
		
		int jsonLength=str[1].length();
		String jsonStr=str[1].substring(0, jsonLength-1);
		JSONObject jsonObj=new JSONObject().getJSONObject(jsonStr);
		Student stu=(Student)JSONObject.toBean(jsonObj,Student.class);
		try {
			Class clazz=Class.forName(className);
			Method method=clazz.getMethod(methodName, Student.class);
			Object result=method.invoke(clazz.newInstance(), stu);
			return result;
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InstantiationException e) {
			e.printStackTrace();
		}
		return false;
	}
}
